﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App.Data;
using App.Core.Extensions;
using System.IO;

public partial class Pages_Private_ContactChange : BasePage
{
    private int _ID = 0;
    private bool _IsEditMode = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        BindPageInfo();
        if (!IsPostBack)
        {
            BindDropDownLists();
            BindContactInfo();
        }
    }
    /// <summary>
    /// Bindis the Page Initialization Variables
    /// </summary>
    protected void BindPageInfo()
    {
        _ID = WebUtil.GetQueryStringInInt(AppConstants.QueryString.ID);
        if (_ID > 0)
        {
            _IsEditMode = true;
            h4Heading.InnerHtml = "Edit Contact";
        }
        Page.Title = WebUtil.GetPageTitle(h4Heading.InnerHtml);
    }

    /// <summary>
    /// Binds Dropdownlists for the initial request.
    /// </summary>
    protected void BindDropDownLists()
    {
        //BindDropdownList.Customers(ddlCustomerID);
        BindDropdownList.Designations(ddlDesignationID);

    }
    /// <summary>
    /// Binds Contact Info Requested through Query Strings
    /// </summary>
    protected void BindContactInfo()
    {
        if (_IsEditMode)
        {
            BtcHousingEntities context = new BtcHousingEntities();
            Contact entity = context.Contacts.FirstOrDefault(P => P.ID == _ID);//dao.GetByID(_ID);
            if (entity == null)
                ShowErrorMessage();
            else
            {
                txtName.Text = entity.Name;
                //txtPhoto.Text = entity.Photo;
                if (!entity.Photo.IsNullOrEmpty())
                {
                    imgPhoto.ImageUrl = String.Format("{0}/{1}", AppConstants.CONTACT_PHOTO, entity.Photo);
                    imgPhoto.Visible = true;
                }
                ddlDesignationID.SetSelectedItem(entity.DesignationID.ToString());
                txtPhone.Text = entity.Phone;
                txtFax.Text = entity.Fax;
                txtEmail.Text = entity.Email;
                //ddlCustomerID.SetSelectedItem(entity.CustomerID.ToString());
                //txtBranchID.Text = entity.BranchID;
                //chkIsDeleted.Checked = entity.IsDeleted;
            }
        }
    }
    /// <summary>
    /// Shows a Message in the UI and Hides the Data Editing Controls
    /// </summary>
    protected void ShowErrorMessage()
    {
        pnlFormContainer.Visible = false;
        WebUtil.ShowMessageBox(divMessage, "Requested Contact was not found.", true);
    }
    protected void SaveContact()
    {
        String photoFileName = null;
        if (fuPhoto.HasFile && !WebUtil.IsValidImageFile(fuPhoto.PostedFile))
        {
            WebUtil.ShowMessageBox(divMessage, "Please Select a Valid Image for Contact Photo.", true);
            return;
        }       
            
        BtcHousingEntities context = new BtcHousingEntities();
        Contact entity = null;

        if (_IsEditMode)
            entity = context.Contacts.FirstOrDefault(P => P.ID == _ID); //dao.GetByID(_ID);        
        else
        {
            entity = new Contact();
            entity.CustomerID = SessionCache.CurrentUser.CustomerID;
            entity.Created = DateTime.Now;
            context.AddToContacts(entity);
        }
        entity.Name = txtName.Text;
        //entity.Photo = txtPhoto.Text;
        entity.DesignationID = ddlDesignationID.SelectedValue.ToInt();
        entity.Phone = txtPhone.Text;
        entity.Fax = txtFax.Text;
        entity.Email = txtEmail.Text;
        //entity.CustomerID = ddlCustomerID.SelectedValue.ToInt();
        //entity.BranchID = txtBranchID.Text;       
        entity.Modified = DateTime.Now;
        entity.ModifiedBy = SessionCache.CurrentUser.ID;
        entity.IsDeleted = false;       

        context.SaveChanges();

        if (fuPhoto.HasFile)
        {
            ///Delete Existing Image first
            if (_IsEditMode && !entity.Photo.IsNullOrEmpty())
            {
                String photoPath = Server.MapPath(AppConstants.CONTACT_PHOTO);
                photoPath = Path.Combine(photoPath, entity.Photo);
                if (File.Exists(photoPath))
                    File.Delete(photoPath);
            }
            photoFileName = String.Format("{0}_{1}", entity.ID, Path.GetFileName(fuPhoto.PostedFile.FileName));
            UploadImage(fuPhoto.PostedFile, AppConstants.CONTACT_PHOTO, photoFileName);
            entity.Photo = photoFileName;
            context.SaveChanges();
        }
        WebUtil.ShowMessageBox(divMessage, "Contact Saved Successfully.", false);
    }

    private void UploadImage(HttpPostedFile httpPostedFile, String path, String outputFileName)
    {
        path = Server.MapPath(path);
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        httpPostedFile.SaveAs(Path.Combine(path, outputFileName));
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            SaveContact();
            Response.Redirect(AppConstants.Pages.CONTACT_LIST);
            return;
        }
    }
    protected void btnList_Click(object sender, EventArgs e)
    {
        Response.Redirect(AppConstants.Pages.CONTACT_LIST);
        return;
    } 
}